package com.bnq.face.face_recognition

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.Rect
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.bnq.face.CameraUtils
import com.bnq.face.FaceActivity
import com.bnq.face.FaceHandleActivity
import com.bnq.face.FaceHandler
import com.bnq.face.ImageUtils
import java.io.File
import java.io.FileOutputStream

class MainActivity : AppCompatActivity() {

    private var f_file:File? = null
    private var o_file:File? = null
    private var h_file:File? = null
    private var t_file:File? = null
    private var image:ImageView? = null

    private var tv:TextView? = null
    private var subtv:TextView? = null

    private val mDefaultInstanceThresh:Double = 20.0
    private val mDefaultMiniThresh:Double = 100.0
    private val mDefaultMaxThresh:Double = 210.0
    private val mDefaultBlueThresh:Double = 80.0
    private val mDefaultIouNormal:Double = 0.8
    private val mDefaultIouInter:Double = 0.35
    private var etDistance:EditText? = null
    private var etMiniThresh:EditText? = null
    private var etMaxThresh:EditText? = null
    private var etBlueThresh:EditText? = null
    private var etIouNormal:EditText? = null
    private var etIouInter:EditText? = null
    private var boxFaceRect:RectBoxView? = null
    private var boxDetRect:RectBoxView? = null
    private var captureContainer:FrameLayout? = null
    private var ivShowImage:ImageView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tv = findViewById<TextView>(R.id.text)
        subtv = findViewById<TextView>(R.id.subtext)
        image = findViewById<ImageView>(R.id.image)
        tv?.text = ImageUtils.getPhoneBrand() + ":" + ImageUtils.getPhoneModel() + ":" + ImageUtils.getPhoneManufacturer() + ":" + ImageUtils.getPhoneDevice()//FaceHandler.getStringForNative()
        etDistance = findViewById(R.id.et_distance)
        etDistance?.setText(mDefaultInstanceThresh.toString())
        etMiniThresh = findViewById(R.id.et_miniThresh)
        etMiniThresh?.setText(mDefaultMiniThresh.toString())
        etMaxThresh = findViewById(R.id.et_maxThresh)
        etMaxThresh?.setText(mDefaultMaxThresh.toString())
        etBlueThresh = findViewById(R.id.et_blueThresh)
        etBlueThresh?.setText(mDefaultBlueThresh.toString())
        etIouNormal = findViewById(R.id.et_iouNormal)
        etIouNormal?.setText(mDefaultIouNormal.toString())
        etIouInter = findViewById(R.id.et_iouInter)
        etIouInter?.setText(mDefaultIouInter.toString())
        boxFaceRect = findViewById(R.id.faceRect)
        boxDetRect = findViewById(R.id.detRect)
        captureContainer = findViewById(R.id.capture_container)
        ivShowImage = findViewById(R.id.show_image)
        o_file = File(getExternalFilesDir(null),"o_1679221812095.jpg")
        assets.open("o_1679221812095.jpg").copyTo(FileOutputStream(o_file))

        f_file = File(getExternalFilesDir(null),"f_1682060458260.jpg")
        assets.open("f_1682060458260.jpg").copyTo(FileOutputStream(f_file))

        h_file = File(getExternalFilesDir(null),"h_1679603226.jpeg")
        Log.e("Face","-----------------------h_file:${h_file?.absolutePath}")
        assets.open("h_1679603226.jpeg").copyTo(FileOutputStream(h_file))

        t_file = File(getExternalFilesDir(null),"test.png")
        Log.e("Face","-----------------------t_file:${t_file?.absolutePath}")
        assets.open("test.png").copyTo(FileOutputStream(t_file))

        //assets.open("mnet.25-opt.param").copyTo(FileOutputStream(File(getExternalFilesDir(null),"mnet.25-opt.param")))
        //assets.open("mnet.25-opt.bin").copyTo(FileOutputStream(File(getExternalFilesDir(null),"mnet.25-opt.bin")))
        setShowContainerRatio()
    }

    private fun setShowContainerRatio(){
        val show_container = findViewById<FrameLayout>(R.id.show_container)
        val lp = show_container.layoutParams
        lp.height = ((180.0 * DensityUtil.getScreenHeight(this) / DensityUtil.getScreenWidth(this)) * DensityUtil.getScreenDensity(this)).toInt()
        show_container.layoutParams = lp
    }

    fun btn_1(view: View) {
        if(o_file != null){
            val startTime = System.currentTimeMillis()
            val result = FaceHandler.computerBlurry(o_file!!.absolutePath)
            val endTime = System.currentTimeMillis()
            tv?.text = result + ", 耗时: ${endTime - startTime}ms"
        }else{
            tv?.text = "图像File == null"
        }

    }
    fun btn_2(view: View) {
        if(f_file != null){
            val result = FaceHandler.computerBlurry(f_file!!.absolutePath)
            tv?.text = result
        }else{
            tv?.text = "图像File == null"
        }
    }
    fun btn_3(view: View) {
        if(h_file != null){
            val result = FaceHandler.computerBlurry(h_file!!.absolutePath)
            tv?.text = result
        }else{
            tv?.text = "图像File == null"
        }
    }

    fun btn_4(view: View) {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(Array<String>(1){Manifest.permission.CAMERA}, 11)
            }else{
                startPreview()
            }
        }else{
            startPreview()
        }
    }

    fun btn_5(view: View) {
        startPreview2()
    }



    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode == 11 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            startPreview()
        }
    }

    private fun startPreview(){
        startActivity(Intent(this,FaceActivity::class.java))
    }

    private fun startPreview2(){
        startActivityForResult(Intent(this,FaceHandleActivity::class.java).apply {
            putExtra("tips","请正对摄像头，保持面部清晰可见")
            putExtra("sub_tips","采集将用于考勤打卡身份验证并严格保护您的隐私信息")
            putExtra("distance_thresh",getDistance())
            putExtra("mini_thresh",getMiniThresh())
            putExtra("max_thresh",getMaxThresh())
            putExtra("blue_thresh",getBlueThresh())
            putExtra("is_compress",true)
            putExtra("iou_normal",getIouNormal())
            putExtra("iou_inter",getIouInter())
            putExtra("can_flip",true)
        },777)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode == 777 && resultCode == RESULT_OK){
            val result = data?.getStringExtra("result_path")
            val compress_result = data?.getStringExtra("result_compress_path")
            tv?.text = result + "\n" + compress_result
            image?.setImageBitmap(BitmapFactory.decodeFile(result))

            val log = data?.getStringExtra("log")

            val faceRect = data?.getParcelableExtra<Rect>("faceRect")
            val detRect = data?.getParcelableExtra<Rect>("detRect")

            subtv?.text = log + "," + "(${faceRect?.left} ${faceRect?.top} ${faceRect?.right} ${faceRect?.bottom})" + "," +"(${detRect?.left} ${detRect?.top} ${detRect?.right} ${detRect?.bottom} )"
            if(faceRect != null){
                boxFaceRect?.setBoxColor(Color.GREEN)
                boxFaceRect?.setRectangle(toShowPx(faceRect.left),toShowPx(faceRect.top),toShowPx(faceRect.right),toShowPx(faceRect.bottom))
            }
            if(detRect != null){
                boxDetRect?.setBoxColor(Color.BLUE)
                boxDetRect?.setRectangle(toShowPx(detRect.left),toShowPx(detRect.top),toShowPx(detRect.right),toShowPx(detRect.bottom))
            }

            ScreenshotUtil.getViewBitmap(captureContainer)?.let {
                ivShowImage?.setImageBitmap(it)
            }
        }
    }

    private fun toShowPx(p:Int):Float{
        return (p/4.0 * DensityUtil.getScreenDensity(this)).toFloat()
    }

    fun btn_6(view: View) {
        if(t_file != null){
            val result = FaceHandler.computerBlurry(t_file!!.absolutePath)
            tv?.text = result
        }else{
            tv?.text = "图像File == null"
        }
    }

    private fun getDistance():Double{
        return try {
            etDistance?.text.toString().toDouble()
        }catch (e:Exception){
            showToast("distanceThresh输入参数有误，使用默认值")
            mDefaultInstanceThresh
        }
    }

    private fun showToast(msg:String){
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
    }

    private fun getMiniThresh():Double{
        return try {
            etMiniThresh?.text.toString().toDouble()
        }catch (e:Exception){
            showToast("miniThresh输入参数有误，使用默认值")
            mDefaultMiniThresh
        }
    }

    private fun getMaxThresh():Double{
        return try {
            etMaxThresh?.text.toString().toDouble()
        }catch (e:Exception){
            showToast("maxThresh输入参数有误，使用默认值")
            mDefaultMaxThresh
        }
    }

    private fun getBlueThresh():Double{
        return try {
            etBlueThresh?.text.toString().toDouble()
        }catch (e:Exception){
            showToast("blueThresh输入参数有误，使用默认值")
            mDefaultBlueThresh
        }
    }

    private fun getIouNormal():Double{
        return try {
            etIouNormal?.text.toString().toDouble()
        }catch (e:Exception){
            showToast("iouNormal输入参数有误，使用默认值")
            mDefaultIouNormal
        }
    }

    private fun getIouInter():Double{
        return try {
            etIouInter?.text.toString().toDouble()
        }catch (e:Exception){
            showToast("iouInter输入参数有误，使用默认值")
            mDefaultIouInter
        }
    }

    fun onDistanceSub(view: View) {
        etDistance?.setText((getDistance() - 1).toString())
    }
    fun onDistanceAdd(view: View) {
        etDistance?.setText((getDistance() + 1).toString())
    }

    fun btn_7(view: View) {
        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
            // 引导用户去设置中手动开启权限
            Toast.makeText(this, "用户拒绝权限，且用户选择了不再询问", Toast.LENGTH_LONG).show()
        }else{
            Toast.makeText(this, "用户拒绝了权限,但未选择不再询问", Toast.LENGTH_LONG).show()
        }
    }

}